import logging
import yaml
from PyQt5.QtWidgets import QMessageBox
import time
import numpy as np

CONFIG_FILE = 'configs/appconfig.yml'

ERROR = -1
INFO = 1
WARNING = 2
DEFAULT = 3


def basic_log_config(debug=True):
    """
    日志输出格式设定
    :param debug: 是否为DEBUG模式
    :return:
    """
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)d - %(message)s"
    DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
    if debug:
        logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT)
    else:
        logFilename = './logs/' + time.strftime("%Y_%m_%d", time.localtime()) + '.log'
        logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT, filename=logFilename,
                            filemode='a')


def load_yaml(filepath=CONFIG_FILE):
    """
    加载yaml配置文件
    :param filepath:
    :return:
    """
    try:
        with open(filepath, 'r') as f:
            data = yaml.load(f, Loader=yaml.SafeLoader)
            return data
    except Exception as e:
        return ERROR, e


def generate_yaml_doc(yaml_file, yaml_obj):
    """
    生成yaml配置文件
    :param yaml_file: 文件路径
    :param yaml_obj: 保存内容，必须为字典格式
    :return:
    """
    if type(yaml_obj).__name__ == 'dict':
        try:
            file = open(yaml_file, 'w', encoding='utf-8')
            yaml.dump(yaml_obj, file)
            file.close()
            return file.name
        except Exception as e:
            return errorhandle.SAVE_YAML_EXCEPTION
    else:
        return errorhandle.SAVE_YAML_DATA_FORMAT_EXCEPTION


def message_box(title, msg):
    """
    # 桌面弹出消息框
    # Python弹出Windows自带的MessageBox
    :param title:
    :param msg:
    :return:
    """
    import ctypes
    ctypes.windll.user32.MessageBoxW(0, msg, title, 1)


def show_dialog(frame, msg, msg_type):
    """
    根据消息类型显示对话框以及提示信息
    :param frame: 对话框框架
    :param msg: 需要显示的信息
    :param msg_type: 信息类型: INFO, WARNING, ERROR
    :return:
    """
    if msg_type == INFO:
        res = QMessageBox.information(frame, "INFO", msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
    elif msg_type == WARNING:
        res = QMessageBox.warning(frame, "WARNING", msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
    elif msg_type == ERROR:
        res = QMessageBox.critical(frame, "ERROR", msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
    if res == QMessageBox.Yes:
        return 0
    else:
        return -1


def save_data(data, filepath='', instType='uwb', filetype='pickle'):
    """
        将数据保存为 pickle或者csv的类型，并以当时时间-数据类型.文件类型 的方式命名
        :param data: 要保存的数据
        :param filepath: 保存的路径
        :param instType: 类型
        :param fileType:文件类型
        :return: 保存成功返回文件命， 保存失败返回错误码
    """
    filename = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime()) + '_' + instType
    if filetype == 'pickle':
        import pickle
        filename = filename + '.pkl'
    if filetype == 'csv':
        import pandas as pd
        filename = filename + '.csv'
    if filetype == 'txt':
        filename = filename + '.txt'
    if not filepath:
        filepath = "./data"
    filepath = filepath + '/' + filename
    try:
        if filetype == 'pickle':
            f = open(filepath, 'wb')
            pickle.dump(data, f)
            f.close()
            return f.name
        if filetype == 'csv':
            save = pd.DataFrame(data)
            save.to_csv(filepath, index=False, header=False)
            return filepath
        if filetype == 'txt':
            f = open(filepath, 'a')
            for i in range(0, len(data)):
                s = data[i]
                f.write(s)
                f.write('\n')
            f.close()
            return f.name
    except Exception as e:
        return errorhandle.SAVE_PICKLE_ERROR


def fmt_mac_addr(macHex):
    reform = ''
    for i in range(0, len(macHex), 2):
        reform = reform + macHex[i:i+2] + '-'
    return reform[0:-1]


def normalization(data):
    M_m = data-np.mean(data)
    return M_m/32767
